package com.idata.service.services;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.idata.model.Builder.KGProxySearchBuilder;
import com.idata.model.dto.KGProxySearchResultDTO;
import com.idata.model.proxyDO.KGDisputeInfoForRelationDO;
import com.idata.model.proxyDO.KGRecommendPersonDO;
import com.idata.model.proxyDO.KGResponseDO;
import com.idata.model.request.QueryRelationTagRequest;
import com.idata.model.request.SearchValueListRequest;
import com.idata.model.response.PageResult;
import com.idata.model.response.PhoneInfoResponse;
import com.idata.service.config.ProxyUrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CitizenInfoService {

    @Autowired
    private ProxyUrlProperties proxyUrlProperties;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据身份证号查询关系
     */
    public Map<String, Map<String, KGDisputeInfoForRelationDO>> proxyGetDisputeRelationMap(List<String> idCardList) {
        String url = this.proxyUrlProperties.getProxyUrl().getKg()
                + "/maotiao_backend/search/getDisputeRelationList";
        ParameterizedTypeReference<KGResponseDO<Map<String, Map<String, KGDisputeInfoForRelationDO>>>> typeReference = new ParameterizedTypeReference<KGResponseDO<Map<String, Map<String, KGDisputeInfoForRelationDO>>>>() {};
        HttpEntity<SearchValueListRequest> requestParam = new HttpEntity<>(new SearchValueListRequest().setSearchValueList(idCardList));
        ResponseEntity<KGResponseDO<Map<String, Map<String, KGDisputeInfoForRelationDO>>>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestParam, typeReference);
        Map<String, Map<String, KGDisputeInfoForRelationDO>> data = responseEntity.getBody().getData();
        return data;
    }

    /**
     * 根据身份证号查询关系列表
     */
    public Map<String, List<String>> proxyGetRelationTagMap(String srcIDNo, List<String> dstIdNo) {
        String url = this.proxyUrlProperties.getProxyUrl().getKg()
                + "/maotiao_backend/search/getRelationTagList";
        ParameterizedTypeReference<KGResponseDO<Map<String, List<String>>>> typeReference = new ParameterizedTypeReference<KGResponseDO<Map<String, List<String>>>>() {};
        HttpEntity<QueryRelationTagRequest> requestParam = new HttpEntity<>(new QueryRelationTagRequest().setSrcValue(srcIDNo).setDstValueList(dstIdNo));
        ResponseEntity<KGResponseDO<Map<String, List<String>>>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestParam, typeReference);
        return responseEntity.getBody().getData();
    }

    /**
     * 根据身份证号查询手机号
     */
    public Map<String, List<PhoneInfoResponse>> proxyGetPhoneMap(List<String> cardNoList) {
        Map<String, List<Entry<String, Integer>>> phoneMap = doProxyGetPhoneMap(cardNoList);
        return Maps.transformValues(phoneMap, phoneList->Lists.transform(phoneList, entry -> new PhoneInfoResponse(entry.getKey(), entry.getValue()))
                .stream().sorted(Comparator.comparingInt(PhoneInfoResponse::getCount).reversed()).collect(Collectors.toList()));
    }

    /**
     * 根据身份证号查询手机号
     */
    private Map<String, List<Map.Entry<String, Integer>>> doProxyGetPhoneMap(List<String> cardNoList) {
        String url = this.proxyUrlProperties.getProxyUrl().getKg()
                + "/maotiao_backend/search/getPhoneList";
        ParameterizedTypeReference<KGResponseDO<Map<String, List<Entry<String, Integer>>>>> typeReference = new ParameterizedTypeReference<KGResponseDO<Map<String, List<Entry<String, Integer>>>>>() {};
        HttpEntity<SearchValueListRequest> requestParam = new HttpEntity<>(new SearchValueListRequest().setSearchValueList(cardNoList));
        ResponseEntity<KGResponseDO<Map<String, List<Entry<String, Integer>>>>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestParam, typeReference);
        return Optional.ofNullable(responseEntity.getBody()).map(KGResponseDO::getData).orElse(new HashMap<>());
    }

    /**
     * 搜索接口，根据身份证号/姓名/手机号 进行 搜索
     */
    public PageResult<KGProxySearchResultDTO> proxySearchCitizen(String text, Integer pageNum, Integer pageSize) {
        String url = this.proxyUrlProperties.getProxyUrl().getKg() +
                String.format("/maotiao_backend/search/list?searchValue=%s&pageNum=%s&pageSize=%s", text, pageNum, pageSize);
        JSONObject jsonObject = this.restTemplate.getForObject(url, JSONObject.class);
        if (jsonObject == null || jsonObject.get("code") == null || !"00000".equals(jsonObject.get("code"))) {
            throw new RuntimeException("接口调用异常");
        }
        Long total = jsonObject.getLong("total");
        List<KGProxySearchResultDTO> kgProxySearchResultDTOS = KGProxySearchBuilder.transferFromJsonObject(jsonObject);
        return new PageResult<>(kgProxySearchResultDTOS, total);
    }

    /**
     * 相关人员接口
     */
    public List<KGRecommendPersonDO> proxyRelatedCitizen(String idNo) {
        String url = this.proxyUrlProperties.getProxyUrl().getKg() +
                String.format("/maotiao_backend/search/getRecommendPersonList?searchValue=%s", idNo);
        ParameterizedTypeReference<KGResponseDO<List<KGRecommendPersonDO>>> typeReference = new ParameterizedTypeReference<KGResponseDO<List<KGRecommendPersonDO>>>() {};
        ResponseEntity<KGResponseDO<List<KGRecommendPersonDO>>> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, typeReference);
        return Optional.ofNullable(responseEntity.getBody()).map(KGResponseDO::getData).orElse(new ArrayList<>());
    }
}
